package cn.kshost.zqyg.manager.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.kshost.zqyg.model.entity.system.SysUser;
import cn.kshost.zqyg.model.vo.common.Result;
import cn.kshost.zqyg.model.vo.common.ResultCodeEnum;
import cn.kshost.zqyg.utils.AuthContextUtil;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.xml.crypto.Data;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  {

        //如果验证是否为预检请求
        if (StrUtil.equalsIgnoreCase("OPTIONS",request.getMethod())) {
            return  true;
        }
        //获取token 如果一个token为空返回没登陆并且拦截
        String token = request.getHeader("token");
        System.err.println("token = " + token);
        if (StrUtil.isEmpty(token)) {
            responseNoLoginInfo(response);
            return false;
        }
        //如果redis通过key找不到返回没登陆
        String sysUserJson = redisTemplate.opsForValue().get("user:login:" + token);
        if (StrUtil.isEmpty(sysUserJson))   {
            responseNoLoginInfo(response);

        }
        //将用户和信息存到ThreadLocal中
        AuthContextUtil.setValue(JSON.parseObject(sysUserJson, SysUser.class));
        //延长token过期时间
        redisTemplate.expire("user:login:" + token,1, TimeUnit.HOURS);
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextUtil.removeVale();
    }

    //将未登录对象转并返回
    void responseNoLoginInfo(HttpServletResponse response )   {
        response.setContentType("application/json;charset=utf-8");
        String jsonString = JSON.toJSONString(Result.build(null, ResultCodeEnum.LOGIN_AUTH));
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.write(jsonString);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

}
